# -*- coding: utf-8 -*-

#-----------------------------------------------------------------------------
# 库文件
#-----------------------------------------------------------------------------

import time
import os
from threading import Thread

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore
import numpy as np

from data_process import read_one_data
from parse_definition import args
from serial_port import *
from log import *

#-----------------------------------------------------------------------------
# 文件变量，参数解析
#-----------------------------------------------------------------------------
# 默认日志文件名称
if (args.log_name):
    log_name = args.log_name  # 自定义文件名
else:
    now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
    log_name = now + ".log"  # 以时间戳作为文件名，以 .log 作为文件格式

# 默认日志文件路径
if (args.log_path):
    log_file_path = args.log_path + log_name
    # 默认配置文件路径
    if (os.path.exists(args.log_path)):
        LOGI("path" + args.log_path + " exists!")
    else:
        os.makedirs(args.log_path)
else:
    log_file_path = "log/" + log_name
    # 默认配置文件路径
    if (os.path.exists('log/')):
        LOGI("path log/ exists!")
    else:
        os.makedirs('log/')

# 数据求和使能与否
if (args.sum_en):
    LOGI("Summation Mode is enabled!")
    x_axis_length = 100
    index = 0
else:
    LOGI("Summation Mode is disabled!")
    if (args.x_axis_length):
        x_axis_length = args.x_axis_length
    else:
        x_axis_length = 100
    index = x_axis_length

# 默认端口，在类unix下使用默认端口
if (args.port):
    port = args.port
else:
    port = '/dev/ttyUSB0'

# 日志数据读取列
if(args.column):
    column = args.column
else:
    column = 2 

# 定时器周期
if (args.update_freq):
    update_period = 1000/args.update_freq
else:
    update_period = 50

# 通信波特率
if (args.baudrate):
    baudrate = args.baudrate
else:
    baudrate = 115200

#-----------------------------------------------------------------------------
# 全局变量
#-----------------------------------------------------------------------------
row = 0
curve = 0
file_name = 0

thread_stop = False

data_to_plot = np.zeros(x_axis_length, dtype=int) 

#-----------------------------------------------------------------------------
# 函数定义
#-----------------------------------------------------------------------------
# 多线程套壳函数
def thread1(sp, log_file_path):
    while (True):
        task_log_printf(sp, log_file_path)
        if (thread_stop):
            break


def update_data_to_plot(file_path, column, row):
    
    # 如果求和使能
    if (args.sum_en):
        global index
        global data_to_plot
        
        # 下标为0时直接使用第一个数，后面所有的均为实时和
        if(index):
            data_to_plot[index] = read_one_data(file_path, column, row) + data_to_plot[index-1]
        else:
            data_to_plot[index] = np.asarray(read_one_data(file_path, column, row)) 
        
        index += 1 # 下标自加

        # 如果下标大于原先的值
        if (index >= data_to_plot.shape[0]) :
            tmp = data_to_plot                                           # 拷贝至tmp
            data_to_plot = np.zeros(data_to_plot.shape[0]*2, dtype=int)  # 将一维矩阵长度扩展为原先的两倍
            data_to_plot[:tmp.shape[0]] = tmp                            # tmp中的值赋值到data_to_plot前半部分

    else:
        tmp = data_to_plot[1:x_axis_length]  # 拷贝后(x_axis_length-1)个数据至tmp
        data_to_plot[:tmp.shape[0]] = tmp    # 将tmp的数据放在data_to_plot的前(x_axis_length-1)位
        data_to_plot[x_axis_length - 1] = read_one_data(file_path, column, row)
        
        
        
# 定时器中断任务
def data_update():
    # 填充数据
    global row, column, file_name
    global curve
    global data_to_plot, index

    update_data_to_plot(file_name, column, row)
    row += 1

    curve.setData(data_to_plot[:index])  # 绘制index个数据


# 主线程
if __name__ == '__main__':

    # 接口打开
    sp = serial_port_open(port, baudrate)

    t1 = Thread(target=thread1, args=(sp, log_file_path))  # 创建后台子线程t1
    file_name = log_file_path                              # 修改变量传递给其他接口

    app = pg.mkQApp("Real Time Plot")  # 创建应用程序

    # 创建窗口并命名
    win = pg.GraphicsLayoutWidget(show=True, title="Real Time Plot")
    win.resize(1200, 600)
    win.setWindowTitle('Real Time Plot')

    # 声明图形绘制
    plot_1 = win.addPlot(title="column#"+str(column))  # 添加图形绘制
    curve = plot_1.plot()                              # 声明曲线

    # 配置周期启动时间
    timer = QtCore.QTimer()             # 启用QtCore里的定时器QTimer
    timer.timeout.connect(data_update)  # 绑定应用程序
    
    # 主线程和子线程启动
    t1.start()                  # 子线程启动
    timer.start(int(update_period))  # 配置周期启动时间（ms）
    
    LOGI("log is reading and app is executing...")
    app.exec()                  # GUI启动（主线程）

    # 主线程结束后子线程也结束
    thread_stop = True
    t1.join()                # 加了这句的话，关闭窗口后需要等待串口结束才能关闭
    serial_port_close(port)  # 关闭串口
